import org.jsecurity.subject.Subject
import org.springframework.web.multipart.MultipartFile
class UserController {
   def loginService
   def jsecSecurityManager
   def imageService
   def login = {
        String email = params.email
        String password = params.password

        if(loginService.authenticate(email,password)){
            redirect(controller:"link")
        }
        else{
            flash.message = "Email and/or password is incorrect!"
            redirect(controller:"link")
        }
    }
    def red = {
        Subject subject = jsecSecurityManager.getSubject()
        log.info("Principal " +(String)subject.getPrincipal())
        redirect(action:"bla")
    }

    def avatarupload = {
         String folder = params.folder
         String dest = "web-app/tmp/avatars/"+folder+"/"
         MultipartFile f = request.getFile('avatar')
         File file = new File(dest)
         boolean createdDir = file.mkdir()
         if(!f.empty){
            log.info("The path where picture will be copied:" +file.absolutePath)
            if(!createdDir){// dir already exists, so delete previous photos of the same user
                if(file.isDirectory()){
                    deleteAllFiles(file)
                }
            }
            String out = file.absolutePath+"\\avatar.jpg";
            file = new File(file.absolutePath+"\\"+f.getName())
            copyImage(file,f.getBytes())
            imageService.avatarResize(file.absolutePath,out)
           
            render("Success!") //have to make a response because of flex

         }
         else
          log.info("Picture is not in jpeg format, or it's empty")
        
       }

    def deleteAllFiles(File dir){
        File [] fl = dir.listFiles()
        for(int i= 0; i < fl.length ; i++){
            log.info("deleting file: rowingmanager.domain.User must have choosen another logo picture")
            (fl[i]).delete()
        }
    }

    def copyImage(File location,byte[] bytes){
       // ByteArrayOutputStream baos = New ByteArrayOutputStream
       log.info("Writing to location:"+location.absolutePath)
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(location))
        try{
            bos.write(bytes)
            bos.flush()
            log.info("Successfully copied the image")
        }catch(IOException e){
            log.info("IO Exception while trying to write bytes into file")
        }finally{
            bos.close()
        }

    }
}
